<template>
	<div id="">
		<a-spin :tip="spinTip" :spinning="spinLoading">
			<div class="header-title">
				用户列表
			</div>
			<!-- 表格数据 -->
			<div class="bg-white m-2 px-2 pt-1">
				<a-row type="flex" justify="space-around" align="middle" class="">
					<!-- 关键词 -->
					<a-col :xs="24"  :md="12" :lg="6">
						<div class="flex align-center my-1 pr-2" @click="click_part(false)">
							<div class="searchtitle">部门/人员：</div>
							<a-input class="cursor-pointer text-ellipsis"  disabled="disabled" v-model="deprtpeo" placeholder="请选择"/>
						</div>
					</a-col>
					<a-col :xs="24"  :md="12" :lg="6">
						<div class="flex align-center pr-2 my-1">
							<div class="searchtitle">关键词：</div>
							<a-input class="" v-model="keyword" placeholder="请输入关键词" />
						</div>
					</a-col>
					<!-- 餐厅选择 -->
					<a-col :xs="24" :sm="12" :md="12" :lg="6">
						<div class="pr-2 flex align-center my-1">
							<a-radio :checked="radiocheck" @click="click_check()">离职人员</a-radio>
							<a-tooltip>
								<template slot="title">
									接入系统之后离职的人员
								</template>
								<a-icon class="tips font15 cursor-pointer" type="exclamation-circle" />
							</a-tooltip>
						</div>
					</a-col>
					<a-col :xs="24" :sm="12" :md="12" :lg="6">
						<div class="flex align-center justify-end my-1 pr-2">
							<a-button type="primary" @click="click_search()">
								查询
							</a-button>
							<a-button class="ml-2" @click="click_reset()">
								重置
							</a-button>
						</div>
					</a-col>
				</a-row>
				
				
				
				
				<!-- <div class="from flex align-center justify-between flex-wrap">
					<div class="flex align-center flex-wrap mt-2">
						<div class="flex align-center">
							<span>部门/人员：</span>
							<div class="normol-width flex justify-between align-center px-1" @click="click_part(false)">
								<div :class="deprtpeo?'text-black':'text-muted'" class="text-ellipsis mr-1">
									{{deprtpeo||'请选择'}}
								</div>
								<a-icon type="down" class="text-muted" />
							</div>
						</div>
						<div class="ml-3">
							<span>关键词：</span>
							<a-input class="normol-width" v-model="keyword" placeholder="请输入关键词" />
						</div>
						<div class="ml-3 flex align-center">
							<a-radio :checked="radiocheck" @click="click_check()">离职人员</a-radio>
							<a-tooltip>
								<template slot="title">
									接入系统之后离职的人员
								</template>
								<a-icon class="tips font15 cursor-pointer" type="exclamation-circle" />
							</a-tooltip>
						</div>
					</div>
					<div class="mt-2">
						<a-button type="primary" @click="click_search()">
							查询
						</a-button>
						<a-button class="ml-2" @click="click_reset()">
							重置
						</a-button>
					</div>
				</div> -->
				
				
				
				
				
				<div class="flex align-center flex-wrap ">
					<a-button type="primary" class="mr-2 mt-1" icon="save" @click="export_data(1)">
						报表导出
					</a-button>
					<a-button icon="pay-circle"  class="mr-2 mt-1" @click="click_showModel()">
						批量充值
					</a-button>
					<a-button type="danger" ghost class="mr-4 mt-1" @click="click_showModel2()">
						清空余额
					</a-button>
					<div class=" text-primary mt-1">
						<list-columns-setter v-model="columns" :def-columns="columns" ref="columnsSetter" colName="2" />
					</div>
				</div>
				
				
				
				<div class="table mt-2">
					<a-table :columns="columns" :data-source="data" @change="pageTableChange" :pagination="pagination"
						:loading='tableLoading' rowKey="id">
					</a-table>
				</div>

			</div>
			<!-- 弹框组件显示 -->
			<div>
				<a-modal v-model="modal1" title="批量充值" centered :okText="upload_text" cancel-text="取消"
					@ok="click_handleOk()" @cancel="click_showModelCancel()" :maskClosable='false'
					:confirmLoading="confirmLoading">
					<div class="px-5 mx-2">
						<a-alert message="请勿编辑模版内除 “充值余额” 以外的信息" type="info" show-icon />
						<div class="flex align-center justify-between my-1">
							<div class="text-black">
								{{filename}}.xlsx
							</div>
							<div>
								<a-button icon="download" class="bg-light" @click="export_data(2)">
									下载模板
								</a-button>

							</div>
						</div>
						<div class="">
							<!-- 上传 -->
							<a-upload-dragger name="file" :file-list="fileList" :before-upload="beforeUpload"
								:remove="delremove">
								<p class="ant-upload-drag-icon text-primary">
									<a-icon type="inbox" />
								</p>
								<div class="font-weight-bold">
									点击或将文件拖拽到这里上传
								</div>
								<div class="ant-upload-hint font-sm">
									该上传文件仅支持扩展名：xlsx
								</div>
							</a-upload-dragger>
							<a-progress v-if="percent>0&&percent<=100" :percent="percent" :strokeWidth="2" />
						</div>
					</div>
				</a-modal>

				<a-modal v-model="modal2" title="清空余额" centered ok-text="确认" cancel-text="取消" @ok="click_handleOk2()"
					@cancel="click_showModel2()" :maskClosable='false' :confirmLoading="false">
					<div class="">
						<a-alert message="此操作不可逆，清空余额后无法恢复该数据" type="info" show-icon />
						<div class="flex align-center my-2">
							<div class="text-black">部门/人员：</div>
							<div id="" @click="click_part(true)">
								<a-input class="cursor-pointer partment-width text-ellipsis"  disabled="disabled" v-model="deprtpeo2" placeholder="全部人员"/>
							</div>
							<!-- <div class=" partment-width  flex justify-between align-center px-1"
								@click="click_part(true)">
								<div :class="deprtpeo2?'text-black':'text-muted'" class="text-ellipsis mr-1">
									{{deprtpeo2||'全部人员'}}
								</div>
								<a-icon type="down" class="text-muted" />
							</div> -->
						</div>
					</div>
				</a-modal>
				<!-- 部门人员弹框 -->
				<chooseDeprt ref="deprtModal" :sonMethod="sonMethod" :sonMethod2="sonMethod2" :empty="partChoose">
				</chooseDeprt>
			</div>
		</a-spin>
	</div>
</template>

<script>
	// 选择部门人员组件
	import chooseDeprt from '@/components/chooseDeprt.vue';
	import ListColumnsSetter from '@/components/ListColumnsSetter'
	export default {
		inject: ['layout'],
		components: {
			chooseDeprt,
			ListColumnsSetter
		},
		data() {
			return {
				data: [], //表格数据
				columns: [{
						title: '编号',
						key: 'rowIndex',
						dataIndex: 'rowIndex',
						align: 'left',
						customRender: (t, r, index) => {
							return parseInt(index) + 1;
						}
					},
					{
						title: '姓名',
						dataIndex: 'name',
						align: 'left',
					},
					{
						title: '工号',
						dataIndex: 'jobnumber',
						align: 'left',
					},
					{
						title: '部门',
						dataIndex: 'department_name',
						align: 'left',
					},
					{
						title: '职位',
						dataIndex: 'position',
						align: 'left',
					},
					{
						title: '部门路径',
						dataIndex: 'department_list_name',
						align: 'left',
					},
					{
						title: '账户余额',
						dataIndex: 'account_money',
						align: 'left',
					},
					{
						title: '在职状态',
						dataIndex: 'isleave',
						align: 'left',
					}
				], //表格列表
				pagination: {
					pageSize: 10, // 一页的数据限制
					current: 1, // 当前页
					total: 10, // 总数
					// hideOnSinglePage: true,
					pageSizeOptions: ['10', '20', '30'],
					showTotal: (total, range) => {
						return '总计：' + total + '条数据'
					},
					showSizeChanger: true
				}, //表格分页
				tableLoading: false, //false
				modal1: false,
				modal2: false,
				modal3: false,
				fileList: [],
				confirmLoading: false,
				upload_text: '确定',
				percent: 0,
				timer: '',
				deprtpeo: '', //请选择部门人员名字
				depart_name_peo: '', //stringify部门人员
				deprtpeo2: '', //清空显示部门人员名字
				depart_name_peo2: '', //清空请选择部门人员tringify
				keyword: '', //请输入关键词
				radiocheck: false, //离职人员单选按钮
				isleave: '0', //是否返回离职人员1否0是
				partChoose: false,
				filename: '充值人员',
				uploadFile: [], //上传文件
				file: [],
				isLoading: false,
				spinTip: '',
				spinLoading: false,
				uploadRate: '',
				emptyRate: ''
			};
		},
		created() {
			this.get_users();
		},
		methods: {

			//table数据分页操作
			pageTableChange(pagination, filters, sorter) {
				this.pagination = pagination
				this.get_users();
				//切换页数重新显示内容
				this.$refs.columnsSetter.initColumns();
			},
			//查询人员
			get_users() {
				// this.layout.showLoading();
				this.data = [];
				this.tableLoading = true;
				axios.post('/account/get_ls', {
					userlst: this.depart_name_peo,
					keyword: this.keyword,
					currentPage: this.pagination.current,
					pageSize: this.pagination.pageSize,
					fiter: '1', //回总数
					isleave: this.isleave, //是否返回离职人员1否0是
				}).then(res => {
					// this.layout.hideLoading();
					this.tableLoading = false;
					if (res.status == 200) {
						// console.log(res.data.data);
						this.pagination.total = res.data.data.count;
						let data = res.data.data.data;
						data.forEach((k) => {
							k.isleave = k.isleave == 0 ? '在职' : '离职';
						})
						this.data = data;
					} else {
						// this.layout.hideLoading();
						this.$message.error(res.data.data.msg);
					}
				}).catch(res => {
					this.tableLoading = false;
					this.$message.error(res);
					console.log(res);
				});
			},
			//点击选择部门人员
			click_part(e) {
				this.partChoose = e;
				this.$refs.deprtModal.openWin();
			},
			//单选框是否选中
			click_check() {
				this.radiocheck = !this.radiocheck;
				this.isleave = this.radiocheck ? '1' : '0';
			},
			// 充值弹框
			click_showModel() {
				this.modal1 = true;
			},
			click_showModelCancel() {
				clearTimeout(this.timer)
				this.confirmLoading = false
				this.modal1 = false;
				this.fileList = [];
				this.percent = 0;
				this.upload_text = '确定';
			},
			//上传之前
			beforeUpload(file) {
				var fileName = file.name.substring(file.name.lastIndexOf('.') + 1)
				if (fileName != 'xlsx' && fileName != 'xls') {
					this.isLoading = false;
					this.$message.error('文件类型必须是xls或xlsx!', 2)
					return false
				}
				if (this.fileList.length > 0) {
					this.fileList.splice(0, 1)
				}
				this.fileList = [...this.fileList, file]
				return false
			},
			// 移除上传记录
			delremove(file) {
				this.fileList = [];
			},
			//确认上传
			click_handleOk() {
				if (this.fileList.length == 0) {
					this.$message.warning('请选择上传文件', 2);
					return;
				}
				var that = this
				const formData = new FormData()
				that.fileList.forEach(file => {
					formData.append('file', file);
				})
				axios.post('/recharge/post_upload_add', formData, {
						headers: {
							'Content-Type': 'multipart/form-data;'
						}
					}).then((res) => {
						that.confirmLoading = true;
						if (res.data.ret == 200) {
							that.timer = setInterval(() => {
								// console.log(res.data);
								let cron_id = res.data.data;
								axios.post('sys/get_cron_stat', {
									cron_id: cron_id
								}).then(res => {
									if (res.data.ret == 200) {
										if (res.data.data.rate < 100) {
											that.percent = res.data.data.rate;
											that.upload_text = '上传中...'
										} else {
											clearTimeout(that.timer);
											that.percent = res.data.data.rate;
											that.confirmLoading = false
											that.upload_text = '上传成功';
											setTimeout(()=>{
												that.fileList = []
												that.$message.success('添加成功!');
												that.percent = 0;
												that.upload_text = '确定';
												that.click_showModelCancel();
												this.get_users();
											},700)
										}
									}
								})
							}, 500);
						}
					})
					.catch((error) => {
						this.$message.error('上传失败', 2)
					})
			},
			handleChange(info) {
				const status = info.file.status;
				if (status !== 'uploading') {
					// console.log(info)
				}
				if (status === 'done') {
					this.$message.success(`${info.file.name} file uploaded successfully.`);
				} else if (status === 'error') {
					this.$message.error(`${info.file.name} file upload failed.`);
				}
			},
			//清空余额一级框显示
			click_showModel2() {
				this.modal2 = !this.modal2;
			},
			// 清空余额一级弹框确认按钮
			click_handleOk2() {
				let user_all = '';
				// 全部用户 1 是 0 否
				if (this.deprtpeo2 == "") {
					user_all = 1;
				} else {
					user_all = 0;
				}
				let that = this;
				this.click_showModel2();
				that.$confirm({
					title: '确定要清空余额吗？',
					content: '清空余额后，将无法恢复，该操作不可逆。',
					centered: true,
					okText: '清空余额',
					onOk() {
						axios.post('/account/post_empty_all', {
							user_all: user_all, //示例： 全部用户 1 是 0 否
							userlst: that.depart_name_peo2,
						}).then(res => {
							if (res.data.ret == 200) {
								// console.log(res.data);
								that.empty_empty(res.data.data);
								// that.$message.info('清空余额成功', 2);
							} else {
								this.$message.error(res.data.msg, 2);
							}
						}).catch(res => {
							// console.log(res);
						});

					},
					onCancel() {},
				});
			},
			// 清空操作
			empty_empty(cron_id) {
				this.spinLoading = true;
				// let message=null;
				let timer = null;
				timer = setInterval(() => {
					// console.log(res.data);
					axios.post('sys/get_cron_stat', {
						cron_id: cron_id
					}).then(res => {
						if (res.data.ret == 200) {
							// console.log(res.data);
							this.spinTip="0%";
							if (res.data.data.rate < 100) {
								this.spinTip = res.data.data.rate + '%';
							} else {
								clearTimeout(timer);
								this.spinTip = res.data.data.rate + '%';
								setTimeout(()=>{
									this.spinLoading = false
									this.$message.success('清空成功!');
									this.click_reset();
								},700)
								
							}
						}
					})
				}, 500);
			},
			//导出报表使用的数据json
			formatJson(filterVal, jsonData) {
				// console.log(jsonData)
				return jsonData.map(v => filterVal.map(j => {
					if (j === 'timestamp') {
						return parseTime(v[j])
					} else {
						return v[j]
					}
				}))
			},
			//导出报表方法
			click_export(exportData) {
				if (exportData == [] || exportData.length == 0) {
					this.$message.error('要导出的数据为空!')
					return;
				}
				//当前时间获取
				let thisTime = this.$util.getCurrentDate(2);
				import('@/vendor/Export2ExcelStyle').then(excel => {
					const tHeader = []; //表头
					const filterVal = []; //表头对应字段
					this.columns.forEach(k => {
						tHeader.push(k.title);
						filterVal.push(k.dataIndex);
					});
					tHeader.splice(0, 1);
					filterVal.splice(0, 1);
					tHeader.splice(2, 0, "userid");
					filterVal.splice(2, 0, "userid");
					const list = exportData;
					list.forEach((k, i) => {
						k.jobnumber = k.jobnumber == null ? "" : k.jobnumber;
						k.name = k.name == null ? "" : k.name;
						k.userid = k.userid == null ? "" : k.userid;
						k.position = k.position == null ? "" : k.position;
						k.department_list_name = k.department_list_name == null ? "" : k
							.department_list_name;
						k.department_name = k.department_name == null ? "" : k.department_name;
						k.account_money = k.account_money == null ? "" : k.account_money;
					});
					const data = this.formatJson(filterVal, list)
					excel.export_json_to_excel({
						title: ["云一就餐_用户明细_" + thisTime],
						header: tHeader,
						data,
						headerStyle: ['A2', 'H2'], //自定义列标题左右样式
						SheetJS: '云一就餐_用户明细', //工作簿名字
						merges: ["A1:H1"], //控制表名字从几到达几。
						bottomTips: ["报表生成时间：" + thisTime, '', '', '', '', '', '', ''],
						filename: "云一就餐_用户明细_" + this.$util.getCurrentDate(3),
						autoWidth: true,
						bookType: 'xlsx'
					})
				})

			},
			//导出报表模板方法
			click_exportModel(exportData) {
				if (exportData == [] || exportData.length == 0) {
					this.$message.error('要导出的数据为空!')
					return
				}
				import('@/vendor/Export2ExcelStyle').then(excel => {
					const title = ["云一就餐_批量充值模版"]; //控制表名。
					const tHeader = ['姓名', '工号', 'userid', '部门路径', '部门', '账户当前余额', '充值金额']; //表头
					const filterVal = ['name', 'jobnumber', 'userid', 'department_list_name', 'department_name',
						'account_money', 'inmoney'
					]; //表头对应字段
					const merges = ["A1:G1"]; //控制表名字从几到达几。
					const list = exportData;
					list.forEach((k, i) => {
						k.jobnumber = k.jobnumber == null ? "" : k.jobnumber;
						k.name = k.name == null ? "" : k.name;
						k.userid = k.userid == null ? "" : k.userid;
						k.department_list_name = k.department_list_name == null ? "" : k
							.department_list_name;
						k.department_name = k.department_name == null ? "" : k.department_name;
						k.account_money = k.account_money == null ? "" : k.account_money;
						k.inmoney = "0";
					});
					const data = this.formatJson(filterVal, list)
					excel.export_json_to_excel({
						title, //标题
						SheetJS: '云一就餐_批量充值模版', //工作簿名字
						header: tHeader, //表格列标题
						merges, //合并单元格标题
						data, //数据
						bottomTips: ['提示：请勿编辑“充值金额”以外的所有信息及样式', '', '', '', '', '', ''],
						headerStyle: ['A2', 'G2'], //自定义列标题左右样式
						filename: '云一就餐_批量充值模版', //导出文件名字
						autoWidth: true, //是否自动列宽
						bookType: 'xlsx' //文件后缀名字
					});
				})
			},
			//导出报表所需数据
			export_data(e) {
				axios.post('/account/get_ls', {
					userlst: this.depart_name_peo,
					keyword: this.keyword,
					fiter: '1', //回总数
					isleave: this.isleave, //是否返回离职人员1否0是
				}).then(res => {
					if (res.status == 200) {
						// console.log(res);
						if (res.data.ret == 200) {
							let data = res.data.data.data;
							data.forEach((k) => {
								k.isleave = k.isleave == 0 ? '在职' : '离职';
							})
							if (e == 1) {
								this.click_export(data)
							} else {
								this.click_exportModel(data)
							}
						}
					}
				}).catch(res => {
					this.$message.error(res);
					console.log(res);
				});
			},
			//查询方法
			click_search() {
				this.get_users();
			},
			//重置方法
			click_reset() {
				this.deprtpeo = '', //
					this.depart_name_peo = '';
				this.keyword = "";
				this.pagination = {
					pageSize: 10, // 一页的数据限制
					current: 1, // 当前页
					total: 10, // 总数
					// hideOnSinglePage: true,
					pageSizeOptions: ['10', '20', '30'],
					showTotal: (total, range) => {
						return '总计：' + total + '条数据'
					},
					showSizeChanger: true
				}
				this.radiocheck = false; //离职人员单选按钮
				this.isleave = '0',
					this.deprtpeo2 = '', //清空显示部门人员名字
					this.depart_name_peo2 = '';
				this.get_users();
			},
			//选择部门/人员
			sonMethod(cancel) {
				// console.log(this.$refs.deprtModal.selectList);
				if (cancel == 'cancel') {
					this.deprtpeo = ''
					return
				}
				if (this.$refs.deprtModal.selectList.users.length == 0 && this.$refs.deprtModal.selectList.departments
					.length == 0) {
					this.deprtpeo = ''
					return
				}
				let deprtpeo = ''
				let depart_name_peo = {
					departments: [],
					users: []
				};
				this.$refs.deprtModal.selectList.departments.forEach((k) => {
					depart_name_peo.departments.push({
						department_id: k.department_id
					});
					if (deprtpeo == '') {
						deprtpeo = deprtpeo + k.name
					} else {
						deprtpeo = deprtpeo + '、' + k.name
					}
				})
				this.$refs.deprtModal.selectList.users.forEach((k) => {
					depart_name_peo.users.push({
						userid: k.userid
					});
					if (deprtpeo == '') {
						deprtpeo = deprtpeo + k.name
					} else {
						deprtpeo = deprtpeo + '、' + k.name
					}
				})
				this.deprtpeo = deprtpeo;
				// this.deprtpeo = JSON.stringify(this.$refs.deprtModal.selectList)
				this.depart_name_peo = depart_name_peo;
				// this.depart_name_peo = JSON.stringify(depart_name_peo);
				// console.log(JSON.stringify(this.$refs.deprtModal.selectList))
			},
			//清空余额选择部门/人员
			sonMethod2(cancel) {
				// console.log(this.$refs.deprtModal.selectList);
				if (cancel == 'cancel') {
					this.deprtpeo2 = ''
					return
				}
				if (this.$refs.deprtModal.selectList.users.length == 0 && this.$refs.deprtModal.selectList.departments
					.length == 0) {
					this.deprtpeo2 = ''
					return
				}
				let deprtpeo = ''
				let depart_name_peo = {
					departments: [],
					users: []
				};
				this.$refs.deprtModal.selectList.departments.forEach((k) => {
					depart_name_peo.departments.push({
						department_id: k.department_id
					});
					if (deprtpeo == '') {
						deprtpeo = deprtpeo + k.name
					} else {
						deprtpeo = deprtpeo + '、' + k.name
					}
				})
				this.$refs.deprtModal.selectList.users.forEach((k) => {
					depart_name_peo.users.push({
						userid: k.userid
					});
					if (deprtpeo == '') {
						deprtpeo = deprtpeo + k.name
					} else {
						deprtpeo = deprtpeo + '、' + k.name
					}
				})
				this.deprtpeo2 = deprtpeo;
				// this.deprtpeo = JSON.stringify(this.$refs.deprtModal.selectList)
				// this.users = this.$refs.deprtModal.selectList.users;
				this.depart_name_peo2 = depart_name_peo;
				// console.log(JSON.stringify(this.$refs.deprtModal.selectList))
			},

		}
	};
</script>

<style scoped>
	.header-title {
		padding: 0 32px;
		height: 50px;
		line-height: 50px;
		font-size: 20px;
		text-align: left;
		font-weight: bold;
		background-color: #FFFFFF;
	}

	.normol-width {
		width: 100%;
		height: 32px;
		border-radius: 5px;
		border: 1px solid #d9d9d9
	}
	.searchtitle {
		text-align: left;
		white-space: nowrap !important;
		/* width: 80px; */
		display: inline-block;
	}
	

	.tips {
		color: #d3d3d3;
	}

	.partment-width {
		margin-left: 50px;
		width: 300px;
		height: 32px;
		border-radius: 5px;
		border: 1px solid #d9d9d9
	}

	::v-deep .ant-table-thead>tr>th,
	.ant-modal-title {
		font-weight: bold !important;
	}

	::v-deep .ant-modal-title {
		font-weight: bold !important;
	}

	::v-deep .ant-alert-info {
		background-color: #EDF5FF;
	}

	::v-deep .ant-modal-confirm-body>.ant-modal-confirm-title {
		font-weight: bold !important;
	}
	::v-deep .ant-input[disabled]{
		background-color: #FFFFFF;
		cursor: pointer;
		color: #000000;
	}
</style>
<!-- // 自定义上传
			customRequest(obj) {
				console.log(obj);
				this.uploadFile = obj;
				// let rep = {
				// 	uid: obj.file.uid,
				// 	name: obj.file.name,
				// 	status: "done",
				// 	// url: window.URL.createObjectURL(obj.file),//上传下载文件
				// 	thumbUrl: window.URL.createObjectURL(obj.file),
				// };
				// this.fileList = [];
				// this.fileList.push(obj.file);
				// console.log(obj.file, window.URL.createObjectURL(obj.file), "pbj");
			},-->
